import axios from "axios"
import { createDiscreteApi } from "naive-ui";

const { message } = createDiscreteApi(
    ["message"]
);


const request = axios.create({
    baseURL: '/api',
    timeout: 5000
})

// 添加请求拦截器
request.interceptors.request.use(config => {

    // 对get请求的参数全部进行URL编码
    let url = config.url
    console.log(url)
    // config.method === 'get'
    if (config.params) {
        url += '?'
        let keys = Object.keys(config.params)
        for (let key of keys) {
            url += `${key}=${encodeURIComponent(config.params[key])}&`
        }
        url = url.substring(0, url.length - 1)
        config.params = {}
    }
    config.url = url
    console.log(url)
    return config;
}, function (error) {
    return Promise.reject(error);
});

// 响应拦截器
request.interceptors.response.use(res => {
    return res;
}, err => {
    // console.log(err.response.data.message);
    // err.response代表错误上的返回对象
    if (err.response.data.message) {
        //使用 naive-ui 的接口弹出错误信息
        message.info(err.response.data.message);
    }
    return Promise.reject(err);
});

export default request;